﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;


using Marbles.Core.Web.Syndication;
using Marbles.Core.Web.Syndication.RSS;
using Marbles.Core.Web.Syndication.Atom;

namespace Marbles.CMS.ContentTypes.Blog
{
    public partial class Renderer : PageRendererBase, IPageRenderer
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        public override void RenderPageContent(PageDefinition Definition)
        {
            ContentManager mgr = new ContentManager();
            List<BlogEntry> items = mgr.GetBlogEntries(Definition);
            RSSFeed rssfeed = new RSSFeed();
            rssfeed.Title = PageDefinition.Title;
            rssfeed.Description = PageDefinition.Description;
            rssfeed.Copyright = PageDefinition.Keywords;
            rssfeed.Link = new Uri(Request.Url.ToString().ToLower().Replace("?rss", string.Empty));
            rssfeed.LastBuildDate = DateTime.Now;

            foreach (BlogEntry item in items)
            {
                rssfeed.Add(item.ToRSS());
            }

            if (Request.Url.Query.ToLower() == "?rss")
            {
                FeedWriter.Write(Response, rssfeed);
                Response.End();
                return;
            }

            if (Request.Url.Query.ToLower() == "?atom")
            {
                AtomFeed feed = new AtomFeed();
                feed.Title = PageDefinition.Title;
                //feed.= PageDefinition.Description;
                feed.Copyright = PageDefinition.Keywords;
                feed.Link = new Uri(Request.Url.ToString().ToLower().Replace("?atom", string.Empty));
                feed.Updated = DateTime.Now;

                foreach (BlogEntry item in items)
                {
                    feed.Add(item.ToAtom());
                }

                FeedWriter.Write(Response, feed);
                Response.End();
                return;
            }

            Marbles.CMS.Controls.BlogView blogctl = Page.LoadControl("~/Controls/BlogView.ascx") as Marbles.CMS.Controls.BlogView;
            blogctl.Items = rssfeed.Items;
            blogctl.DataBind();
            AddContentToPlaceHolder("ContentBody", new CompiledTemplateBuilder(new BuildTemplateMethod(delegate(Control c) { c.Controls.Add(blogctl); })));


        }

    }
}
